package com.hm.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hm.ruiji.common.R;
import com.hm.ruiji.entity.User;
import com.hm.ruiji.service.UserService;
import com.hm.ruiji.util.SendMailUtil;
import com.hm.ruiji.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Value("${ruiji.send}")
    private String SENDER;

    @Autowired
    private JavaMailSender sender;

    public String send(String to, String subject, String content) {

        // 获取消息对象
        MimeMessage mimeMessage = sender.createMimeMessage();

        // 创建一个消息帮助对象
        MimeMessageHelper helper = null;

        try {

            helper = new MimeMessageHelper(mimeMessage, true);

            // 设置发送人
            helper.setFrom(SENDER);

            // 设置收件人
            helper.setTo(to);

            // 设置主题
            helper.setSubject(subject);

            // 设置内容
            helper.setText(content);

            //// 设置上传附件
            //helper.addAttachment(file.getOriginalFilename(), file);

            sender.send(mimeMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
        }

        return "成功";

    }

    /**
     * 发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMail(@RequestBody User user, HttpSession session) {
        /*
         *   获取邮箱地址
         *   因为短信验证需要付费所以这里用的是QQ邮箱验证
         *   phone   即邮箱地址
         */
        String mail = user.getPhone();
        log.info("邮箱地址：{}", mail);

        if (StringUtils.isNotEmpty(mail)) {
            // 生成验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            log.info("生成验证码：code=【{}】", code);

            // 发送邮件
            send(mail,"【瑞吉外卖】", "您本次登录的验证码为： 【" + code + "】 ，如非本人操作，请勿泄露给他人！");

            // 将验证码存入session
            session.setAttribute(mail, code);
            // 设置验证码有效期，单位为秒s
            session.setMaxInactiveInterval(5*60);

            return R.success(code);
        }
        return R.error("邮箱为空地址，发送失败");
    }

    /**
     * 客户端登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {

        log.info("用户登录信息：{}", map.toString());

        // 获取手机号
        String phone = map.get("phone");
        // 获取验证码
        String code = map.get("code");
        // 获取session里的验证码
        Object s_code = session.getAttribute(phone);
        String v_code = (String) session.getAttribute(phone);
        // 比对验证码
        if (s_code != null && s_code.equals(code)){
            // 判断是否为新用户
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = userService.getOne(wrapper);
            // 如果是新用户自动完成注册
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            return R.success(user);
        }

        return R.error("验证码错误，登录失败");
    }
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}
